package com.dgty.dg_common.network

import android.util.Log
import com.aleyn.mvvm.adapter.FlowAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Title: RetrofitManager.kt
 * Description:
 * Created DateTime: 2023-02-08
 * Created by xxl.
 */
object RetrofitManager {

    //    private const val BASE_URL = "http://test-api.duoguan.cc/"
//    private const val BASE_URL = "http://47.251.37.59/"
    private const val BASE_URL = "https://api.powerbridge.cc/"

    private var retrofit: Retrofit

    init {

        val logInterceptor = HttpLoggingInterceptor {
            Log.d("OkHttp Log : ", it)
        }.setLevel(HttpLoggingInterceptor.Level.BODY)

        val okHttpClient = OkHttpClient().newBuilder()
            .callTimeout(20, TimeUnit.SECONDS)
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
//            .followRedirects(false)
            .cookieJar(MyCookieJar())
            .addInterceptor(logInterceptor)
            .addInterceptor(HeadersInterceptor())
            .addInterceptor(TokenInterceptor())
            .build()

        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(FlowAdapterFactory.create(true))
            .addConverterFactory(GsonConverterFactory.create())
//            .addConverterFactory(CoroutineCallAdapterFactory())
            .build()

    }


    fun <T> getService(service: Class<T>): T {
        return retrofit.create(service)
    }
}